import copy
import random

from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework import status

from common.constant.ResultConstant import ResultEnum
from common.utils.JwtUtil import JwtUtil
from common.config.JwtConfig import JwtConfig

from production_line.models import *
import logging
import hashlib
from common.utils.MD5 import md5

logger = logging.getLogger('mylogger')


@api_view(['GET'])
def resultful(request):
    data = {
        'name': 'resultful',
        'age': 20,
        'gender': 'male',
        'hobby': 'coding',
        'address': 'shanghai',
    }
    # 返回成功无数据
    # return Response(status=status.HTTP_200_OK)

    # 返回成功有数据
    return Response(data, status=status.HTTP_200_OK)

    # 返回失败
    #
    # return Response(ResultEnum.BAD_REQUEST, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
def login(request):
    # 假设请求数据为JSON格式，包含 'account' 和 'password' 字段
    # 获取用户账号和密码
    account = request.POST.get('account')
    password = request.POST.get('password')
    logger.info('登录账号: ' + account)

    # 检查数据库是否有此用户
    user = Employee.objects.filter(account=account, password=md5(password)).first()

    # 如果没有 返回需要注册
    if not user:
        # 用户不存在，可以返回需要注册的信息
        return Response(ResultEnum.INVALID_PASSWORD_401)
    else:  # 如果存在
        token_data = {
            'id': user.id,
            'account': user.account,
            'employee_name': user.employee_name,
        }
        token = JwtUtil.create_jwt(JwtConfig.admin_secret_key, JwtConfig.admin_ttl, token_data)
        return Response(token)


@api_view(['POST'])
def register(request):
    # 获取用户账号和密码
    account = request.POST.get('account')
    password = request.POST.get('password')
    logger.info('注册账号: ' + account)

    # 判断库中是否存在此账号
    if Employee.objects.filter(account=account).first():
        # 如果账号已存在，返回错误响应
        return Response(ResultEnum.CREATED_201)

    # 创建新用户
    new_emp = Employee(account=account, password=md5(password))
    # 在将密码保存到数据库之前对其进行哈希处理
    new_emp.save()

    return Response(ResultEnum.SUCCESS_200)

@api_view(['GET'])
def set_test_data(request):
    """设置测试数据"""
    # for i in range(11, 20):
    #     j = random.randint(1000000, 9999999)
    #
    #     new_product = Product(name='测试产品' + str(i), item_code=str(i), size='SK-' + str(j),
    #                           description='产品' + str(i),
    #                           is_combination=False, production_status='未生产')
    #     new_product.save()

    # 基本产品生成
    # for i in range(11,20):
    #     new_product = BasicProduct(name='基本测试产品' + str(i), description="基本测试产品" + str(i))
    #     new_product.save()

    # 基本产品和组合产品联系生成
    # 查询产品表中为组合产品的id
    # for product in Product.objects.filter(is_combination=1):
    #     for basic_product in BasicProduct.objects.all():
    #         new_combination = CombinationBasicRel(combination_product=product, basic_product=basic_product)
    #         new_combination.save()

    # for product in Product.objects.filter(is_combination=1):
    #     for basic_product in BasicProduct.objects.all():
    #         new_combination = CombinationBasicRel(combination_product=product, basic_product=basic_product)
    #         new_combination.save()

    return Response(ResultEnum.SUCCESS_200)


@api_view(['GET'])
def product_detail(request):
    item_code = request.GET.get('product_item_code')
    try:
        product = Product.objects.get(item_code=item_code)
        production_records = ProductionRecord.objects.filter(product=product)
        records_data = []
        for record in production_records:
            records_data.append({
                'id': record.id,
                'result': record.result,
                'end_time': record.end_time.strftime('%Y-%m-%d %H:%M:%S'),
            })
        response_data = {
            'id': product.id,
            'name': product.name,
            'item_code': product.item_code,
            'size': product.size,
            'description': product.description,
            'is_combination': product.is_combination,
            'production_status': product.production_status,
            'production_records': records_data,
        }
    except Product.DoesNotExist:
        return Response(ResultEnum.INTERNAL_ERROR_500)

    return Response(response_data)
